package com.qf.controller;



import com.qf.util.Constants;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/*
    Dell
    2021/9/27
    12:53
*/
@WebServlet(name = "BaseController")
public class BaseController extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获得一个类对象
        Class self = this.getClass();
        //收参
        String method = req.getParameter("method");
        try {
            Method method1 = self.getMethod(method, HttpServletRequest.class, HttpServletResponse.class);
            String invoke = (String) method1.invoke(this, req, resp);
            //统一处理结果
            if(invoke!=null){
                if(invoke.startsWith(Constants.FORWARD)){//转发
                    String path = invoke.substring(invoke.indexOf(":") + 1);
                    req.getRequestDispatcher(path).forward(req,resp);
                }else if(invoke.startsWith(Constants.REDIRECT)){//重定向
                    String path = invoke.substring(invoke.indexOf(":") + 1);
                    resp.sendRedirect(req.getContextPath()+path);
                }else{//响应结果给页面
                    resp.getWriter().println(invoke);
                }
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
